package com.cyy.operation.request;

import io.restassured.http.Method;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

import static io.restassured.RestAssured.baseURI;
import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

@Data
@Component
@Slf4j
public class HTTP {
    private String path;
    private Method method;
    private Map<String, String> headers = new HashMap<>();
    private String parameters;
    private Map<Object, Object> payload = new HashMap<>();
    RequestSpecification specification;

    public void setBaseURI(String base) {
        baseURI = base;
    }

    /**
     * 设置headers的值
     *
     * @param key   key键
     * @param value 设置的值
     */
    public void setHeaders(String key, String value) {
        this.headers.put(key, value);
    }

    public void setPayload(String key, Object value) {
        this.payload.put(key, value);
    }

    /**
     * 发送请求
     */
    public Response send() {

        // 检查变量是否准备好
        assertThat("path不能为空，请设置", StringUtils.isEmpty(path), equalTo(false));
        assertThat("method不能为空，请设置", StringUtils.isEmpty(method), equalTo(false));

        specification = given().headers(headers).body(payload);
        if (!StringUtils.isEmpty(parameters)) path += "?" + parameters;

        Response response = specification.request(method, path).peek();
        // 打印消息
        String message = String.format("\n%s: %s\nHeaders:\n%s\nParameters:\n%s\nPayload:\n%s\n\nResponse:\n%s",
                method.toString(), baseURI + path,
                headers.toString(), parameters,
                payload.toString(), response.asString());
        log.info(message);
        // 清除参数
        path = null;
        method = null;
        headers.clear();
        parameters = null;
        payload = new HashMap<>();
        return response;
    }


}
